/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * Copyright (C) 2016-2020 the AndroidAnnotations project
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.helper;

import org.ohosannotations.ElementValidation;
import org.ohosannotations.annotations.ResId;
import org.ohosannotations.rclass.IRClass.Res;

import java.util.List;
import java.util.Set;

import javax.lang.model.element.Element;

/**
 * IdValidatorHelper
 *
 * @since 2021-07-20
 */
public class IdValidatorHelper extends ValidatorHelper {
    private final IdAnnotationHelper idAnnotationHelper;

    /**
     * 构造参数
     *
     * @param idAnnotationHelper id注解助手
     */
    public IdValidatorHelper(IdAnnotationHelper idAnnotationHelper) {
        super(idAnnotationHelper);
        this.idAnnotationHelper = idAnnotationHelper;
    }

    /**
     * 回退策略
     * FallbackStrategy
     *
     * @author dev
     * @since 2021-07-23
     */
    public enum FallbackStrategy {
        /**
         * 使用元素名称
         */
        USE_ELEMENT_NAME,
        /**
         * 允许没有res id
         */
        ALLOW_NO_RES_ID,
        /**
         * 需要res id
         */
        NEED_RES_ID
    }

    /**
     * resIdsExist
     *
     * @param element 元素
     * @param res 资源
     * @param fallbackStrategy 回调策略
     * @param valid 元素验证
     */
    public void resIdsExist(Element element, Res res, FallbackStrategy fallbackStrategy, ElementValidation valid) {
        String annotationName = idAnnotationHelper.getTarget();
        int[] resIds = idAnnotationHelper.extractAnnotationResIdValueParameter(element, annotationName);

        if (idAnnotationHelper.defaultResIdValue(resIds)) {
            idValidator(element, res, fallbackStrategy, valid, annotationName);
        } else {
            for (int resId : resIds) {
                if (!idAnnotationHelper.containsIdValue(resId)) {
                    valid.addError("Resource id value not found in R." + res.rName() + ": " + resId);
                }
            }
        }
    }

    private void idValidator(Element element, Res res,
        FallbackStrategy fallbackStrategy, ElementValidation valid, String annotationName) {
        String[] resNames = idAnnotationHelper.extractAnnotationResNameParameter(element, annotationName);

        if (idAnnotationHelper.defaultResName(resNames)) {
            if (fallbackStrategy == FallbackStrategy.USE_ELEMENT_NAME) {
                /*
                 * fallback, using element name
                 */
                String elementName = idAnnotationHelper.extractElementName(element, annotationName);
                String name = RnameTool.humpToLine2(elementName);
                elementName = reName(elementName, res);
                name = reName(name, res);
                if (!idAnnotationHelper.containsField(elementName) && !idAnnotationHelper.containsField(name)) {
                    valid.addError("Resource name not found in R." + res.rName() + ": " + elementName);
                }
            } else if (fallbackStrategy == FallbackStrategy.NEED_RES_ID) {
                valid.addError("%s needs an annotation value");
            } else {
            }
        } else {
            for (String resName : resNames) {
                resName = reName(resName, res);
                if (!idAnnotationHelper.containsField(resName)) {
                    valid.addError("Resource name not found in R." + res.rName() + ": " + resName);
                }
            }
        }
    }

    /**
     * reName
     *
     * @param elementName elementName
     * @param res res
     * @return res
     */
    private String reName(String elementName, Res res) {
        return res.rName() + "_" + elementName;
    }

    /**
     * OptionalValidResId
     *
     * @param element element
     * @param res res
     * @param parameterName parameterName
     * @param valid valid
     */
    public void annotationParameterIsOptionalValidResId(Element element,
        Res res, String parameterName, ElementValidation valid) {
        Integer resId = annotationHelper.extractAnnotationParameter(element, parameterName);
        if (!resId.equals(ResId.DEFAULT_VALUE) && !idAnnotationHelper.containsIdValue(resId)) {
            valid.addError("Id value not found in R." + res.rName() + ": " + resId);
        }
    }

    /**
     * uniqueResourceId
     *
     * @param element element
     * @param resourceType resourceType
     * @param valid valid
     */
    public void uniqueResourceId(Element element, Res resourceType, ElementValidation valid) {
        if (valid.isValid()) {
            List<String> annotationQualifiedIds = idAnnotationHelper
                .extractAnnotationResources(element, resourceType, true);

            Element elementEnclosingElement = element.getEnclosingElement();
            Set<? extends Element> annotatedElements = validatedModel()
                .getRootAnnotatedElements(annotationHelper.getTarget());
            for (Element uniqueCheckElement : annotatedElements) {
                Element uniqueCheckEnclosingElement = uniqueCheckElement.getEnclosingElement();
                if (elementEnclosingElement.equals(uniqueCheckEnclosingElement)) {
                    List<String> checkQualifiedIds = idAnnotationHelper
                        .extractAnnotationResources(uniqueCheckElement, resourceType, true);
                    for (String checkQualifiedId : checkQualifiedIds) {
                        for (String annotationQualifiedId : annotationQualifiedIds) {
                            if (annotationQualifiedId.equals(checkQualifiedId)) {
                                String annotationSimpleId = annotationQualifiedId.substring(annotationQualifiedId.lastIndexOf('.') + 1);
                                valid.addError("The resource id " + annotationSimpleId + " is already used on the following "
                                    + annotationHelper.annotationName() + " method: " + uniqueCheckElement);
                                return;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * uniqueId
     *
     * @param element element
     * @param valid valid
     */
    public void uniqueId(Element element, ElementValidation valid) {
        uniqueResourceId(element, Res.ID, valid);
    }

    /**
     * annotationValuePositiveAndInAShort
     *
     * @param value value
     * @param valid valid
     */
    public void annotationValuePositiveAndInAShort(int value, ElementValidation valid) {
        if (value < 0 || value > 0xFFFF) {
            valid.addError("Due to a restriction in the fragment API," +
                " the requestCode has to be a positive integer inferior or equal to 0xFFFF");
        }
    }
}
